package base

/*
* @author: hjz
* @time: 2025/4/28 21:35
* 先计算出每个链表的长度，然后对齐两个链表，然后同时遍历
 */
func getIntersectionNode(headA, headB *ListNode) *ListNode {
	lenA := ListNodeLen(headA)
	lenB := ListNodeLen(headB)

	// 对齐两个链表
	for lenA > lenB {
		headA = headA.Next
		lenA--
	}
	for lenB > lenA {
		headB = headB.Next
		lenB--
	}

	// 同时遍历两个链表，寻找相交节点
	for headA != nil && headB != nil {
		if headA == headB {
			return headA
		}
		headA = headA.Next
		headB = headB.Next
	}

	return nil
}

func ListNodeLen(head *ListNode) int {
	if head == nil {
		return 0
	}
	return ListNodeLen(head.Next) + 1
}
